package com.project;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.MapView.LayoutParams;

public class MapView extends MapActivity {

	MapController mapController;
	DBHelper dbHelp;
	private Bundle bundle;
	private int itemId;
	private Cursor cur;
	private TextView myLocationText;
	private String out = "";
	
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mapview);
		
		myLocationText = (TextView) findViewById(R.id.myLocationText);
		bundle = this.getIntent().getExtras();
		itemId = bundle.getInt("id");
		dbHelp = new DBHelper(this);
		
		com.google.android.maps.MapView myMapView = (com.google.android.maps.MapView)findViewById(R.id.myMapView);
		mapController = myMapView.getController();
		
		List<Overlay> mapOverlays = myMapView.getOverlays();
		/*
		 * Class Context getResources() Return a Resources instance for your
		 * application's package.
		 * 
		 * Class Resource getDrawable(int id) Return a drawable object
		 * associated with a particular resource ID.
		 */
		
		Drawable drawable = this.getResources().getDrawable(R.drawable.pp);
		HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
		
		dbHelp = new DBHelper(this);
		//Toast.makeText(this, dbHelp.countRow()+"", Toast.LENGTH_SHORT).show();
		
		try{
			cur = dbHelp.showPin(itemId);
			while (cur.moveToNext()) {
				Double lat = cur.getDouble(cur.getColumnIndex("lat"));
				Double lng = cur.getDouble(cur.getColumnIndex("lng"));
				
				GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
				 
				OverlayItem overlayitem = new OverlayItem(point,cur.getString(cur.getColumnIndex("name")), null);
	
				itemizedoverlay.addOverlay(overlayitem);
				out += "Place Name : "+cur.getString(cur.getColumnIndex("name"))+"\n";
				out += "Description : "+cur.getString(cur.getColumnIndex("description"));
			}
			mapOverlays.add(itemizedoverlay);
			myLocationText.setText(out);
		}catch(Exception ex){
			//Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
		}
		
		// Zoom MapView
		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
		View zoomView = myMapView.getZoomControls();
		/*
		 * Class View void addView(View child, ViewGroup.LayoutParams params)
		 * Adds a child view with the specified layout parameters.
		 */
		zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		myMapView.displayZoomControls(true);

		// Location Management
		LocationManager locationManager;
		/*
		 * class Context String final LOCATION_SERVICE Use with
		 * getSystemService(String) to retrieve a LocationManager for
		 * controlling location updates.
		 */
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(context);

		/*
		 * Class Criteria
		 * 
		 * final int ACCURACY_FINE A constant indicating a finer location
		 * accuracy requirement final int POWER_LOW A constant indicating a low
		 * power requirement.
		 * 
		 * Criteria() Constructs a new Criteria object.
		 * 
		 * void setAccuracy(int accuracy) Indicates the desired accuracy for
		 * latitude and longitude. void setAltitudeRequired(boolean
		 * altitudeRequired) Indicates whether the provider must provide
		 * altitude information. void setBearingRequired(boolean
		 * bearingRequired) Indicates whether the provider must provide bearing
		 * information. void setCostAllowed(boolean costAllowed) Indicates
		 * whether the provider is allowed to incur monetary cost. void
		 * setPowerRequirement(int level) Indicates the desired maximum power
		 * level.
		 */
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		/*
		 * Class LocationManager
		 * 
		 * String getBestProvider(Criteria criteria, boolean enabledOnly)
		 * Returns the name of the provider that best meets the given criteria.
		 * Location getLastKnownLocation(String provider) Returns a Location
		 * indicating the data from the last known location fix obtained from
		 * the given provider.
		 */
		String provider = locationManager.getBestProvider(criteria, true);

		Location location = locationManager.getLastKnownLocation(provider);
		updateWithNewLocation(location);
		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListener);

	}

	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private void updateWithNewLocation(Location location) {
		String latLongString;
		TextView myLocationText;
		myLocationText = (TextView) findViewById(R.id.myLocationText);

		/*
		 * Class Location
		 * 
		 * Double getLatitude() Returns the latitude of this fix. Double
		 * getLongitude() Returns the longitude of this fix.
		 */
		if (location != null) {

			// Update the map location
			Double geoLat = location.getLatitude() * 1E6;
			Double geoLng = location.getLongitude() * 1E6;
			GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
			mapController.animateTo(point);

			double lat = location.getLatitude()*1E6;
			double lng = location.getLongitude()*1E6;
			latLongString = "Lat:" + lat + "\nLong:" + lng;
		} else {
			latLongString = "No location found";
		}
		myLocationText.setText("Your Current Position is:\n" + latLongString);
	}

	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}

		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	// Must Intent but Intent work with Activity Class
	public class HelloItemizedOverlay extends com.google.android.maps.ItemizedOverlay {

		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
		Context mContext;

		public HelloItemizedOverlay(Drawable defaultMarker) {
			/*
			 * boundCenterBottom(android.graphics.drawable.Drawable balloon)
			 * Adjusts a drawable's bounds so that (0,0) is a pixel in the
			 * center of the bottom row of the drawable.
			 */
			super(boundCenterBottom(defaultMarker));
		}

		public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
			super(boundCenterBottom(defaultMarker));
			mContext = context;
		}

		public void addOverlay(OverlayItem overlay) {
			mOverlays.add(overlay);
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mOverlays.get(i);
		}

		@Override
		public int size() {
			return mOverlays.size();
		}

		@Override
		protected boolean onTap(int index) {
			OverlayItem item = mOverlays.get(index);
			AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			dialog.setTitle(item.getTitle());
			dialog.setMessage(item.getSnippet());
			dialog.setCancelable(false).setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try{
						Bundle bundle = new Bundle();
						Cursor cur = dbHelp.showPin(itemId);
						while (cur.moveToNext()) {
							String name = cur.getString(cur.getColumnIndex(DBHelper.colName));
							String des = cur.getString(cur.getColumnIndex(DBHelper.colDescription));
							String pic = cur.getString(cur.getColumnIndex(DBHelper.colPicture));
							bundle.putString("id", itemId+"");
							bundle.putString("name", name);
							bundle.putString("detail", des);
							bundle.putString("pic", pic);
							//Toast.makeText(MapView.this, name+des+pic, Toast.LENGTH_SHORT).show();
						}
						Intent intent = new Intent(MapView.this, ShowDetail.class);
						intent.putExtras(bundle);
						startActivity(intent);
					}
					catch(Exception e){
						
					}
				}
			}).setNegativeButton("No",
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			dialog.show();
			return true;
		}
	}
}
